import axios from "axios";
import router from "@/router/index";
const instance = axios.create({
  baseURL: import.meta.env.VITE_HTTP_URL,
  timeout: 2 * 60 * 1000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 每个请求头都带一个这个参数
    config.headers.kongCheckTestKeyAuth = "Ky]=k4{GYNZxn}1%j#TS";
    if (sessionStorage.getItem("operateToken")) {
      config.headers.Authorization = `${sessionStorage.getItem(
        "operateToken"
      )}`;
    }
    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (response) => {
    if (response.status === 200 && response.data.code == 200) {
      return Promise.resolve(response.data);
    } else {
      if (response.data.code == 401) {
        ElMessage.error("登陆失效，即将跳转至登陆页面");
        setTimeout(() => {
          router.push("/login");
        }, 1000);
      } else {
        ElMessage.error(response.data.msg || "请联系管理员");
      }
    }
  },
  (error) => {
    let err = error.response?.data || {};
    ElMessage.error(err.message || "请联系管理员");
    return Promise.reject(error);
  }
);

export default instance;
